package com.human.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.human.dao.EmpMapper;
import com.human.dao.MenuMapper;
import com.human.entity.Emp;
import com.human.entity.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author jzq
 * @date 2023/3/11 16:43
 */
@SuppressWarnings({"all"})
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    EmpMapper empMapper;

    @Resource
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUserName, userName);
        Emp emp = empMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(emp)) {
            throw new RuntimeException("用户不存在");
        }
        //判断用户账号是否禁用
        if (emp.getStatus() == 0) {
            throw  new RuntimeException("账号已禁用");
        }
        // 根据用户ID查询权限
        List<String> list = menuMapper.selectPermsByEmpId(emp.getId());
        //把数据封装成UserDetails返回
        return new LoginUser(emp, list);
    }

}
